<template>
  <div class="login-container">
    <div class="login-view-form">
      <h1>{{ $t("ui.register.title") }}</h1>
      <div class="login-link">
        <span>{{ $t("ui.register.existingAccount") }}</span>
        <a-button type="link" @click="cancel">{{
          $t("ui.login.login")
          }}</a-button>
      </div>
      <a-form :model="formState" @submit.prevent="handleSubmit">
        <a-form-item>
          <a-input v-model:value="formState.username" :placeholder="$t('ui.login.username')">
            <template #prefix>
              <user-outlined />
            </template>
            <template #suffix>
              <a-tooltip :title="$t('ui.login.clear')">
                <close-outlined class="pointer-icon" @click="clearUsername" style="color: rgba(0, 0, 0, 0.45)" />
              </a-tooltip>
            </template>
          </a-input>
          <div v-if="submitted && usernameError" class="error-message">
            {{ usernameError }}
          </div>
        </a-form-item>
        <a-form-item>
          <a-input type="email" v-model:value="formState.email" :placeholder="$t('ui.login.email')">
            <template #prefix>
              <mail-outlined />
            </template>
            <template #suffix>
              <a-tooltip :title="$t('ui.login.clear')">
                <close-outlined class="pointer-icon" @click="clearEmail" style="color: rgba(0, 0, 0, 0.45)" />
              </a-tooltip>
            </template>
          </a-input>
          <div v-if="submitted && emailError" class="error-message">
            {{ emailError }}
          </div>
        </a-form-item>
        <a-form-item>
          <a-input-password v-model:value="formState.password" :placeholder="$t('ui.login.password')">
            <template #prefix>
              <lock-outlined />
            </template>
          </a-input-password>
          <div v-if="submitted && passwordError" class="error-message">
            {{ passwordError }}
          </div>
        </a-form-item>
        <a-form-item>
          <a-input-password v-model:value="formState.confirmPassword" :placeholder="$t('ui.login.confirm-password')">
            <template #prefix>
              <lock-outlined />
            </template>
          </a-input-password>
          <div v-if="submitted && confirmPasswordError" class="error-message">
            {{ confirmPasswordError }}
          </div>
        </a-form-item>
        <a-form-item>
          <!-- <a-button @click="cancel">{{ $t("ui.login.cancel") }}</a-button> -->
          <a-button type="primary" htmlType="submit" style="width: 100%">{{
            $t("ui.register.register")
            }}</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router"; // 导入 useRouter
import { useI18n } from "vue-i18n";
import {
  Form,
  FormItem,
  Input,
  InputPassword,
  Button,
  Tooltip,
} from "ant-design-vue";
import {
  UserOutlined,
  MailOutlined,
  CloseOutlined,
  LockOutlined,
} from "@ant-design/icons-vue"; // 导入图标

export default defineComponent({
  name: "RegisterForm",
  components: {
    "a-form": Form,
    "a-form-item": FormItem,
    "a-input": Input,
    "a-input-password": InputPassword,
    "a-button": Button,
    "a-tooltip": Tooltip,
    UserOutlined,
    MailOutlined,
    LockOutlined,
    CloseOutlined,
  },
  setup() {
    const { t } = useI18n(); // 获取 t 函数和 locale
    const store = useStore();
    const router = useRouter(); // 获取路由实例
    // 使用 Getters 获取 formState
    const formState = computed(() => store.getters["users/getFormState"]);
    const submitted = ref(false); // 新增一个ref变量跟踪提交状态
    // 其他的 computed 属性和方法
    const usernameError = computed(() =>
      formState.value.username.length > 3
        ? ""
        : t("ui.register.usernameMinLength")
    );
    const emailError = computed(() =>
      formState.value.email.includes("@") ? "" : t("ui.register.invalidEmail")
    );
    const passwordError = computed(() =>
      formState.value.password.length > 5
        ? ""
        : t("ui.register.passwordMinLength")
    );
    const confirmPasswordError = computed(() =>
      formState.value.confirmPassword === formState.value.password
        ? ""
        : t("ui.register.passwordsDoNotMatch")
    );
    // 验证状态
    const usernameValidateStatus = computed(() =>
      usernameError.value ? "error" : ""
    );
    const emailValidateStatus = computed(() =>
      emailError.value ? "error" : ""
    );
    const passwordValidateStatus = computed(() =>
      passwordError.value ? "error" : ""
    );
    const confirmPasswordValidateStatus = computed(() =>
      confirmPasswordError.value ? "error" : ""
    );
    // const verificationCode = ref("");

    const handleSubmit = () => {
      console.log("handleSubmit");
      submitted.value = true; // 在验证前将submitted设置为true
      // store.commit("users/setIsRegistering", false); // 触发 Vuex mutation
      if (
        !usernameError.value &&
        !emailError.value &&
        !passwordError.value &&
        !confirmPasswordError.value
      ) {
        store.dispatch("users/registerUser", {
          userData: {
            username: formState.value.username,
            name: formState.value.username,
            email: formState.value.email,
            password: formState.value.password,
          },
        });
        store.commit("users/setIsRegistering", false); // 触发 Vuex mutation
      }
    };
    // 取消操作
    const cancel = () => {
      // 清空表单数据
      formState.value.username = "";
      formState.value.password = "";
      formState.value.email = "";
      formState.value.confirmPassword = "";
      store.commit("users/setIsRegistering", false); // 触发 Vuex mutation
      router.push("/login"); // 登录成功后跳转到 Home 页面
      // 这里可以执行其他操作，例如跳转到登录页面
      console.log("取消操作");
    };
    const clearUsername = () => {
      formState.value.username = "";
    };
    const clearEmail = () => {
      formState.value.email = "";
    };
    return {
      formState,
      usernameError,
      emailError,
      passwordError,
      confirmPasswordError,
      usernameValidateStatus,
      emailValidateStatus,
      passwordValidateStatus,
      confirmPasswordValidateStatus,
      handleSubmit,
      cancel,
      submitted, // 将submitted添加到返回对象中
      clearUsername,
      clearEmail,
    };
  },
});
</script>

<style scoped>
.error-message {
  color: red;
}

.login-container {
  display: flex;
  /* 使用 Flexbox */
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  margin: 10vh;
  background-color: var(--bg-color);
  color: var(--info-color);
}

.login-view-form {
  width: 280px;
  /* background: white; 可选：表单背景颜色 */
  padding: 20px;
  /* 可选：内边距 */
  border-radius: 8px;
  /* 可选：圆角 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  /* 可选：阴影效果 */
}

.tabs-container {
  display: flex;
  /* 使用 Flexbox */
  justify-content: center;
  /* 水平居中 */
  /* margin-bottom: 16px; 添加底部间距 */
}

.flex-container {
  display: flex;
  /* 使用 Flexbox */
  justify-content: space-between;
  /* 使子项左右分离 */
  align-items: center;
  /* 垂直居中对齐 */
}

.verification-container {
  display: flex;
  /* 使用 Flexbox */
  width: 100%;
  /* 容器宽度为 100% */
}

.verification-container .ant-input {
  margin-right: 8px;
  /* 输入框和按钮之间的间距 */
}

/* 鼠标悬停时变为指针形状 */
.pointer-icon {
  cursor: pointer;
  /* 设置光标为 pointer */
}
</style>
